package com.shigu.trade.service;

import com.opentae.data.mall.beans.*;
import com.opentae.data.mall.interfaces.*;
import com.opentae.data.mall.pojo.OrderData;
import com.shigu.PageResponse;
import com.shigu.account.api.VipManagerService;
import com.shigu.account.enums.UserType;
import com.shigu.account.enums.VipLevel;
import com.shigu.appVersion.service.VersionService;
import com.shigu.item.enums.ImgRule;
import com.shigu.trade.enums.OrderState;
import com.shigu.trade.enums.OrderTimeType;
import com.shigu.trade.enums.TradeStatus;
import com.shigu.trade.vo.TradeLogisticsResponse;
import com.shigu.trade.vo.TradeOrder;
import com.shigu.trade.vo.TradeOrderResponse;
import com.shigu.trade.vo.TradeReceiveResponse;
import com.shigu.util.MoneyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TradeWapService {

    @Autowired
    MallOrderMapper mallOrderMapper;
    @Autowired
    MallTradeMapper mallTradeMapper;
    @Autowired
    MallOrderLogisticsMapper mallOrderLogisticsMapper;
    @Autowired
    MallOrderRecordMapper mallOrderRecordMapper;
    @Autowired
    ManagerMallUserMapper managerMallUserMapper;

    @Resource(name = "vipManagerServiceImpl")
    VipManagerService vipManagerService;

    @Autowired
    UserInviteInfoMapper userInviteInfoMapper;

    @Autowired
    VersionService versionService;

    /**
     * 　 订单物流
     *
     * @author 郭尔
     * @date 2019/1/10 15:51
     */
    public TradeReceiveResponse tradeReceiveDetail(String tradeCode) {
        MallOrderLogistics info = mallOrderLogisticsMapper.selectByTradeCode(tradeCode);
        TradeReceiveResponse response = new TradeReceiveResponse();
        response.setAddrdetail(info.getAddressDetail());
        response.setAreaName(info.getAreaName());
        response.setCityName(info.getCityName());
        response.setProvName(info.getProvName());
        response.setReceivePhone(info.getReceiveTelephone());
        response.setReceiver(info.getReceiveName());
        return response.success();
    }

    /**
     * 订单信息
     *
     * @author 郭尔
     * @date 2019/1/10 15:54
     */
    public TradeOrderResponse tradeOrderDetail(String tradeCode,String version,String os) {
        MallOrder mallOrder = mallOrderMapper.selectOrderByTradeCode(tradeCode);
        MallTrade trade = mallTradeMapper.selByTradeCode(tradeCode);
        OrderState state = judgeOrderState(trade.getTradeStatus(),trade.getPayStatus(),trade.getSendStatus());

        ManagerMallUser user = managerMallUserMapper.selectByPrimaryKey(trade.getBuyerId());
        Integer dis = 100;
        VipLevel level = VipLevel.COMMON;
        if(user.getUserType() == UserType.APP.getValue()){
            UserInviteInfo info = userInviteInfoMapper.selectByPrimaryKey(trade.getBuyerId());
            level = VipLevel.selByValue(info.getVipLevel());
            String uri = versionService.versionUri(version, os);
            dis= vipManagerService.vipDiscount(trade.getBuyerId(),uri);
        }
        Double discount = Double.valueOf(dis) / 100; //除以100 用于计算

        TradeOrderResponse response = new TradeOrderResponse();
        response.setTitle(mallOrder.getTitle());
        response.setImgUrl(mallOrder.getImgUrl());
        response.setItemId(mallOrder.getItemId());
        response.setSku(mallOrder.getSku());
        response.setNum(mallOrder.getNum());
        response.setDiscount(MoneyUtil.formatPriceMoney(mallOrder.getDiscount()));
        response.setMoney(MoneyUtil.formatPriceMoney(mallOrder.getPayMoney()+mallOrder.getPostFee()));

        response.setPostFee(MoneyUtil.formatPriceMoney(mallOrder.getPostFee()));
        //
        response.setVipDiscount(MoneyUtil.formatMoney(mallOrder.getDiscount()*discount));
        if(!dis.equals(100)){// 折扣不等于 100(原价)
            response.setVipDiscountNum(Double.valueOf(dis)/10 +"");
        }

        response.setState(state.getValue());
        response.setDutiesName(level.getTitle());
        return response.success();
    }

    /**
     * 订单列表
     *
     * @author 郭尔
     * @date 2019/1/10 16:02
     */
    public PageResponse<TradeOrder> tradeOrderList(Long userId, int page, int size, int status) {
        List<OrderData> list = mallOrderMapper.selOrderList((page - 1) * size, size, userId, status);
        int total = mallOrderMapper.countOrderList(userId, status);
        PageResponse<TradeOrder> response = new PageResponse<>();

        response.setTotal(total);
        response.setHasNext(total > page * size);
        response.setData(list.stream().map(o -> {
            TradeOrder vo = new TradeOrder();
            vo.setOrderId(o.getOrderId());
            vo.setItemId(o.getItemId());
            vo.setImgUrl(o.getImgUrl()+ImgRule.rule1.getText());
            vo.setMoney(MoneyUtil.formatPriceMoney(o.getPayMoney()+o.getPostFee()));
            vo.setPostFee(MoneyUtil.formatPriceMoney(o.getPostFee()));
            vo.setTitle(o.getTitle());
            vo.setTradeCode(o.getTradeCode());
            OrderState state = judgeOrderState(o.getTradeStatus(),o.getPayStatus(),o.getSendStatus());
            vo.setState(state.getValue());
            return vo;
        }).collect(Collectors.toList()));

        return response.success();
    }

    /**
     * @description 判断订单状态
     * @author 郭尔
     * @date 2019/1/26 9:58
     */
    public OrderState judgeOrderState(Integer tradeStatus, Integer payStatus, Integer sendStatus){
        if(tradeStatus == TradeStatus.COMPLETED.getValue()){
            return  OrderState.COMPELETE;
        }else if(tradeStatus == TradeStatus.COMFIRM.getValue()){
            /*
             * 确认订单后 trade_status =1
             * 待付款 pay=0 send=0
             * 待发货 pay=1 send=0
             * 待收货 pay=1 send=1
             * 总和 为
             * */
            Integer flag = tradeStatus+payStatus+sendStatus;
            return OrderState.selByValue(flag);
        }
        return OrderState.CLOSED;
    }
    

    /**
     * @description
     * @author 郭尔
     * @date 2019/1/24 11:05
     */
    public TradeLogisticsResponse tradeLogistics(String tradeCode) {
        MallOrderLogistics info = mallOrderLogisticsMapper.selectByTradeCode(tradeCode);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        TradeLogisticsResponse response = new TradeLogisticsResponse();

        if (StringUtils.isNotBlank(info.getPostCode())) {
            response.setPostCode(info.getPostCode());
        }
        if (StringUtils.isNotBlank(info.getPostCompany())) {
            response.setPostCompany(info.getPostCompany());
        }

        Date createTime = mallOrderRecordMapper.selOrderTime(OrderTimeType.CREATETIME.getValue(), tradeCode);
        Date payTime = mallOrderRecordMapper.selOrderTime(OrderTimeType.PAYTIME.getValue(), tradeCode);
        Date deliverTime = mallOrderRecordMapper.selOrderTime(OrderTimeType.DELIVERTIME.getValue(), tradeCode);
        Date receiveTime = mallOrderRecordMapper.selOrderTime(OrderTimeType.RECEIVETIME.getValue(), tradeCode);

        response.setCreateTime(sdf.format(createTime));
        if (payTime != null) {
            response.setPayTime(sdf.format(payTime));
        }
        if (deliverTime != null) {
            response.setDeliverTime(sdf.format(deliverTime));
        }
        if (receiveTime != null) {
            response.setReceiveTime(sdf.format(receiveTime));
        }
        return response.success();
    }

}
